'use strict';

const { Controller } = require('egg');

class UserInfoController extends Controller {
  async check() {
    const ctx = this.ctx;
    const helper = ctx.helper;
    const { username, password, code, rememberMe } = ctx.request.body;

    ctx.set('Content-Type', 'application/json');

    if (code !== ctx.session.login_code) {
      ctx.state = 403;
      ctx.body = { code: 403, msg: '验证码不正确！' };
      return;
    }else {
      const userInfo = await ctx.service.userInfo.check({ username, password: helper.md5(password) });

      if (!userInfo) {
        ctx.state = 403;
        ctx.body = { code: 403, msg: '用户名或密码不正确！' };
      } else if( userInfo.enable < 1) {
        ctx.state = 403;
        ctx.body = { code: 403, msg: `当前用户 ${userInfo.username} 已被禁用！` };        
      } else {
        ctx.session.userName = userInfo.username;
        ctx.session.userId = userInfo.id;
        ctx.session.loginTime = Date.now();
        ctx.session.maxAge = rememberMe ? 24 * 3600 * 1000 * 3 : 4 * 3600 * 1000 // 3天 || 4h   
  
        ctx.state = 200;
        ctx.body = { code: 200, data: userInfo };
      }
    }
  }

  async change() {
    const { ctx } = this;
    let dataList = {};
    await this.ctx.render('login.njk', dataList);
  }
}

module.exports = UserInfoController;
